import React, { useState } from 'react';
import { Form, Input, Button, Typography, Space, Divider, message } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
import { CustomFrame } from '../components/CustomFrame';
import { useNavigate } from 'react-router-dom';
import { register } from '../services/auth'; 
import { RegisterParams } from '../types/auth';
import { AxiosError } from 'axios';

const { Title } = Typography;

export const RegisterPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: RegisterParams) => {
    setLoading(true);
    try {
      await register({ username: values.username, password: values.password, email: values.email });
      message.success('注册成功！正在跳转到登录页面...');
      setTimeout(() => {
        navigate('/login');
      }, 1500);
    } catch (error) {
      const axiosError = error as AxiosError<{ message: string }>;
      const errorMessage = axiosError.response?.data?.message || '注册失败，请检查您的网络或联系管理员';
      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <CustomFrame title="创建账户">
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        padding: '32px', 
        height: '100%',
        boxSizing: 'border-box'
      }}>
        <Space direction="vertical" align="center" style={{ width: '100%', flex: 1, justifyContent: 'center' }}>
          <Title level={3} style={{ color: 'rgba(255, 255, 255, 0.85)', marginBottom: '32px' }}>开启您的旅程</Title>
          <Form
            name="register"
            style={{ width: '300px' }}
            onFinish={onFinish}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入您的用户名!' }]}
            >
              <Input prefix={<UserOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />} placeholder="用户名" size="large" />
            </Form.Item>
            <Form.Item
              name="email"
              rules={[{ type: 'email', message: '请输入有效的邮箱地址!' }]}
            >
              <Input prefix={<MailOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />} placeholder="邮箱 (可选)" size="large" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入您的密码!' }]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />}
                type="password"
                placeholder="密码"
                size="large"
              />
            </Form.Item>
            <Form.Item
              name="confirm"
              dependencies={['password']}
              hasFeedback
              rules={[
                { required: true, message: '请确认您的密码!' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不匹配!'));
                  },
                }),
              ]}
            >
              <Input.Password 
                prefix={<LockOutlined style={{ color: 'rgba(255, 255, 255, 0.45)' }} />}
                placeholder="确认密码" 
                size="large" 
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%' }} size="large" block>
                注 册
              </Button>
            </Form.Item>
          </Form>
        </Space>
        <Divider style={{ margin: '16px 0' }}>
            <span style={{color: 'rgba(255, 255, 255, 0.45)'}}>已有账户?</span>
        </Divider>
        <Button type="link" onClick={() => navigate('/login')}>返回登录</Button>
      </div>
    </CustomFrame>
  );
}; 